import Toast from 'tdesign-miniprogram/toast/index';
import {
  orderDetailNew
} from '~/services/api/order'
import {
  cosThumb
} from '~/utils/util';
// import {
//   getAddressPromise
// } from '../../../pages/usercenter/address/list/util';

Page({
  addressPromise: [],
  data: {
    pageLoading: true,
    order: {}, // 后台返回的原始数据
    _order: {}, // 内部使用和提供给 order-card 的数据
    storeDetail: {},
    countDownTime: null,
    addressEditable: false,
    backRefresh: false, // 用于接收其他页面back时的状态
    formatCreateTime: '', //格式化订单创建时间
    logisticsNodes: [],
    /** 订单评论状态 */
    orderHasCommented: true,
  },

  onLoad(query) {
    this.orderNo = query.orderNo;
    this.init();
    this.navbar = this.selectComponent('#navbar');
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');
  },

  onShow() {
    // 当从其他页面返回，并且 backRefresh 被置为 true 时，刷新数据
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({
      backRefresh: false
    });
  },

  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },

  onImgError(e) {
    if (e.detail) {
      console.error('img 加载失败');
    }
  },

  // 页面初始化，会展示pageLoading
  init() {
    this.setData({
      pageLoading: true
    });
    this.getDetail()
  },

  // 页面刷新，展示下拉刷新
  onRefresh() {
    this.init();
    // 如果上一页为订单列表，通知其刷新数据
    const pages = getCurrentPages();
    const lastPage = pages[pages.length - 2];
    if (lastPage) {
      lastPage.data.backRefresh = true;
    }
  },

  // 页面刷新，展示下拉刷新
  onPullDownRefresh_(e) {
    const {
      callback
    } = e.detail;
    return this.getDetail().then(() => callback && callback());
  },

  async getDetail() {
    let {
      data
    } = await orderDetailNew({
      orderId: this.orderNo
    });
    data.goodsList = data.orderProductList.map((goods) => ({
      id: goods.productId,
      thumb: cosThumb(goods.productPic, 70),
      title: goods.productName,
      price: goods.price,
      unitPrice: goods.unitPrice,
      productDesc: goods.productDesc,
      num: goods.num,
      productSpec: goods.productSpec
    }));
    console.log(data);
    // goodsList: (order.orderProductList).map((goods) => ({
    //   id: goods.productId,
    //   thumb: cosThumb(goods.productPic, 70),
    //   title: goods.productName,
    //   price: goods.price,
    //   unitPrice:goods.unitPrice,
    //   productDesc:goods.productDesc,
    //   num:goods.num,
    //   productSpec:goods.productSpec
    // })),

    console.log(data.placeTime, 'data.placeTime');
    this.setData({
      order: data,
      // formatCreateTime:data.placeTime? formatTime(
      //   parseFloat(`${data.placeTime}`),
      //   'YYYY-MM-DD HH:mm',
      // ):"暂无", // 格式化订单创建时间
      // invoiceDesc: order.invoiceDesc,
      // invoiceType: order.invoiceVO?.invoiceType === 5 ? '电子普通发票' : '不开发票', //是否开票 0-不开 5-电子发票
    });
  },

  // 展开物流节点
  flattenNodes(nodes) {

  },

  datermineInvoiceStatus(order) {
    // 1-已开票
    // 2-未开票（可补开）
    // 3-未开票
    // 4-门店不支持开票
    return order.invoiceStatus;
  },

  // 拼接省市区
  composeAddress(order) {
    return [
        //order.logisticsVO.receiverProvince,
        order.logisticsVO.receiverCity,
        order.logisticsVO.receiverCountry,
        order.logisticsVO.receiverArea,
        order.logisticsVO.receiverAddress,
      ]
      .filter((s) => !!s)
      .join(' ');
  },

  getStoreDetail() {
    fetchBusinessTime().then((res) => {
      const storeDetail = {
        storeTel: res.data.telphone,
        storeBusiness: res.data.businessTime.join('\n'),
      };
      this.setData({
        storeDetail
      });
    });
  },

  // 仅对待支付状态计算付款倒计时
  // 返回时间若是大于2020.01.01，说明返回的是关闭时间，否则说明返回的直接就是剩余时间
  computeCountDownTime(order) {
    if (order.orderStatus !== OrderStatus.PENDING_PAYMENT) return null;
    return order.autoCancelTime > 1577808000000 ?
      order.autoCancelTime - Date.now() :
      order.autoCancelTime;
  },

  onCountDownFinish() {
    //this.setData({ countDownTime: -1 });
    const {
      countDownTime,
      order
    } = this.data;
    if (
      countDownTime > 0 ||
      (order && order.groupInfoVo && order.groupInfoVo.residueTime > 0)
    ) {
      this.onRefresh();
    }
  },

  onGoodsCardTap(e) {
    const {
      index
    } = e.currentTarget.dataset;
    const goods = this.data.order.orderItemVOs[index];
    wx.navigateTo({
      url: `/subpages/pages/goods/details/index?spuId=${goods.spuId}`
    });
  },
  getAddressPromise() {
    let resolver;
    let rejecter;
    const nextPromise = new Promise((resolve, reject) => {
      resolver = resolve;
      rejecter = reject;
    });
    addressPromise.push({
      resolver,
      rejecter
    });
    return nextPromise;
  },

  onEditAddressTap() {
    this.getAddressPromise()
      .then((address) => {
        this.setData({
          'order.logisticsVO.receiverName': address.name,
          'order.logisticsVO.receiverPhone': address.phone,
          '_order.receiverAddress': address.address,
        });
      })
      .catch(() => {});

    wx.navigateTo({
      url: `/pages/usercenter/address/list/index?selectMode=1`,
    });
  },

  onOrderNumCopy() {
    wx.setClipboardData({
      data: this.data.order.orderNo,
    });
  },

  onDeliveryNumCopy() {
    wx.setClipboardData({
      data: this.data.order.logisticsVO.logisticsNo,
    });
  },

  onToInvoice() {
    wx.navigateTo({
      url: `/pages/order/invoice/index?orderNo=${this.data._order.orderNo}`,
    });
  },

  onSuppleMentInvoice() {
    wx.navigateTo({
      url: `/pages/order/receipt/index?orderNo=${this.data._order.orderNo}`,
    });
  },

  onDeliveryClick() {
    const logisticsData = {
      nodes: this.data.logisticsNodes,
      company: this.data.order.logisticsVO.logisticsCompanyName,
      logisticsNo: this.data.order.logisticsVO.logisticsNo,
      phoneNumber: this.data.order.logisticsVO.logisticsCompanyTel,
    };
    wx.navigateTo({
      url: `/pages/order/delivery-detail/index?data=${encodeURIComponent(
        JSON.stringify(logisticsData),
      )}`,
    });
  },

  /** 跳转订单评价 */
  navToCommentCreate() {
    wx.navigateTo({
      url: `/pages/order/createComment/index?orderNo=${this.orderNo}`,
    });
  },

  /** 跳转拼团详情/分享页*/
  toGrouponDetail() {
    wx.showToast({
      title: '点击了拼团'
    });
  },

  clickService() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '您点击了联系客服',
    });
  },

  onOrderInvoiceView() {
    wx.navigateTo({
      url: `/pages/order/invoice/index?orderNo=${this.orderNo}`,
    });
  },
});